package database

import (
	"snake/app/model/database"
	"errors"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/util/gconv"
	"snake/app/constants"
	"snake/app/service/log"
	"snake/library"
	"snake/library/base"
)

type Request struct {
	database.Entity
	UserId int `form:"userId" json:"userId"`
}

func GetById(id int64) (*database.Entity, error) {
	if id <= 0 {
		glog.Error(" get id error")
		return new(database.Entity), errors.New("参数不合法!")
	}
	return database.Model.FindOne(" id = ?", id)
}


func GetOne(form *base.BaseForm) (*database.Entity, error) {
	where := " 1 = 1 "
	var params []interface{}
	if form.Params != nil && form.Params["id"] != "" {
		where += " and id = ? "
		params = append(params, gconv.Int(form.Params["id"]))
	}
	if form.Params != nil && form.Params["userId"] != "" {
		where += " and user_id = ? "
		params = append(params, gconv.Int(form.Params["userId"]))
	}
	return database.Model.FindOne(where, params)
}


func Delete(id int64, userId int) (int64, error) {
	if id <= 0 {
		glog.Error("delete id error")
		return 0, errors.New("参数不合法!")
	}
	r, err1 := database.Model.Delete(" id = ?", id)
	if err1 != nil {
		return 0, err1
	}
	return r.RowsAffected()
}


func Save(request *Request) (int64, error) {
	entity := (*database.Entity)(nil)
	err := gconv.Struct(request.Entity, &entity)
	if err != nil {
		return 0, errors.New("添加失败")
	}
	entity.UpdateId = request.UserId
	entity.UpdateTime = library.GetNow()

	if entity.Id <= 0 {
		entity.CreateId = request.UserId
		entity.CreateTime = library.GetNow()
		r, err := database.Model.Insert(entity)
		if err != nil {
			glog.Error(err)
			return 0, err
		}

		lastId, err := r.LastInsertId()
		if err != nil {
			glog.Error(err)
			return 0, err
		}
		entity.Id = gconv.Int(lastId)

		return r.RowsAffected()
	} else {
		r, err := database.Model.OmitEmpty().Where(" id = ?", entity.Id).Update(entity)
		if err != nil {
			return 0, err
		}
		log.SaveLog(entity, constants.UPDATE)
		return r.RowsAffected()
	}
}


func List(form *base.BaseForm) ([]*database.Entity, error) {
	where := " 1 = 1 "
	var params []interface{}
	if form.Params != nil && form.Params["host"] != "" {
		where += " and host like ? "
		params = append(params, "%"+form.Params["host"]+"%")
	}
	if form.Params != nil && form.Params["system_name"] != "" {
		where += " and system_name like ? "
		params = append(params, "%"+form.Params["system_name"]+"%")
	}
	if form.Params != nil && form.Params["owner"] != "" {
		where += " and owner = ? "
		params = append(params, gconv.Int(form.Params["owner"]))
	}
	return database.Model.Order(form.OrderBy).FindAll(where, params)
}


func Page(form *base.BaseForm) ([]database.Entity, error) {
	if form.Page <= 0 || form.Rows <= 0 {
		glog.Error("page param error", form.Page, form.Rows)
		return []database.Entity{}, nil
	} else {
		glog.Debug("query form:", form)
	}
	where := " 1 = 1 "
	var params []interface{}
	if form.Params != nil && form.Params["host"] != "" {
		where += " and host like ? "
		params = append(params, "%"+form.Params["host"]+"%")
	}
	if form.Params != nil && form.Params["port"] != "" {
		where += " and port like ? "
		params = append(params, "%"+form.Params["port"]+"%")
	}
	if form.Params != nil && form.Params["env"] != "" {
		where += " and env = ? "
		params = append(params, form.Params["env"])
	}
	if form.Params != nil && form.Params["system_name"] != "" {
		where += " and system_name like ? "
		params = append(params, "%"+ form.Params["system_name"]+"%")
	}
	num, err := database.Model.As("t").FindCount(where, params)
	form.TotalSize = num
	form.TotalPage = num / form.Rows

	if err != nil {
		glog.Error("page count error", err)
		return []database.Entity{}, err
	}

	if num == 0 {
		form.TotalPage = 0
		form.TotalSize = 0
		return []database.Entity{}, err
	}

	var resData []database.Entity
	dbModel := database.Model.As("t").Fields(database.Model.Columns() + ",su1.real_name as owner,su2.real_name as createName")
	dbModel = dbModel.LeftJoin("sys_user su1", " t.update_id = su1.id ")
	dbModel = dbModel.LeftJoin("sys_user su2", " t.create_id = su2.id ")
	err = dbModel.Where(where, params).Order(form.OrderBy).Page(form.Page, form.Rows).M.Structs(&resData)
	if err != nil {
		glog.Error("page list error", err)
		return []database.Entity{}, err
	} else {
		glog.Debug("sql query resdata:", resData)
	}

	return resData, nil
}
